<template>
  <div>
    <ZContainer :noPadding="true" :noBorder="true" class="mail">
      <div style="margin:10px 0;display: flex;justify-content: space-between;">
        <div>
          <el-button style="width:100px" @click="deleteMore" type="danger" size="mini">Delete</el-button>
          <el-button style="width:100px" @click="openDialog" type="primary" size="mini">Add</el-button>
        </div>
        <el-input style="width:300px" @input="keyWordsChange" v-model="keyValue" placeholder="Search"
          prefix-icon="el-icon-search"></el-input>
      </div>
      <el-table ref="multipleTable" :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="username" label="UserName">
        </el-table-column>
        <el-table-column prop="host" label="Host Name">
        </el-table-column>
        <el-table-column prop="status" label="Status">
          <template slot-scope="scope">
            <el-tag size="small" style="width:90px;text-align: center;" :type="scope.row.status ? 'success' : 'danger'">{{
              scope.row.status ? 'Verified' : 'Not Verified' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="Action">
          <template slot-scope="scope">
            <el-button style="padding:0" icon="cuifont icon_edit" @click="handleClick(scope.row)" type="text"
              size="small"></el-button>
            <el-button style="padding:0" icon="cuifont icon_mail_send" @click="postEmailVerify(scope.row)" type="text"
              size="small"></el-button>
            <el-button style="padding:0" icon="cuifont icon_delete" type="text" @click="deleteSmtp([scope.row])"
              size="small"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination layout="total,prev, pager, next" :total="total" background :page-size="size"
        :current-page='currentPage' @current-change="handleCurrentChange">
      </el-pagination>
    </ZContainer>
    <el-dialog :title="isEdit ? 'Edit' : 'Add'" :visible.sync="dialogVisible" width="45%" @close="closeHanlder"
      :close-on-click-modal="false" show-close>
      <el-alert v-if="isEdit" :closable="false"
      title="Note: Prior to email verification, emails will be sent from the MSPbots support email address."
      type="error">
    </el-alert>
      <UserFormMaking :key="JSON.stringify(userformData.id)" ref="userFormMaking" :visible="true" @envent="handleEvent"
        :userformData="userformData" @setSignature="setSignature">
        <template #quill-editor>
          <div style="margin-top:20px">Signature</div>
          <!-- <quill-editor style="height:315px;margin-top: 20px;" ref="myTextEditor"
            v-model="userformData.javaMailProperties_mail_smtp_signing" :options="editorOption"></quill-editor> -->
            <ZTinymce v-if="dialogVisible" style="margin-top: 20px;" v-model="javaMailProperties_mail_smtp_signing"
                ref="myTextEditor"
                :height="50" />
        </template>
        <template v-slot:email-btn>
          <div style="display:flex;justify-content: flex-end;margin-top: 20px;">
            <el-button size="mini" type="primary" @click="add">Confirm</el-button>
            <el-button size="mini" @click="handleTestConnection" :loading="connectionloading">Test Connection</el-button>
          </div>
        </template>
      </UserFormMaking>
    </el-dialog>
  </div>
</template>

<script>
import ZContainer from '@/components/storybook/z-container'
import UserFormMaking from '@/components/form-making/userFormMaking.vue'
import config from '@/utils/config'
import { debounce } from 'lodash'
import ZTinymce from '@/components/storybook/z-tinymce/index.vue'
export default {
  name: 'mail',
  components: {
    ZContainer,
    UserFormMaking,
    ZTinymce
  },
  data () {
    return {
      tableData: [],
      loading: false,
      currentPage: 1,
      size: 10,
      total: 0,
      dialogVisible: false,
      userformData: {
        formTitle: null,
        formCode: null,
        id: null,
      },
      javaMailProperties_mail_smtp_signing: '',
      result: {},
      connectionloading: false,
      isEdit: false,
      keyValue: '',
      editorOption: {
        name: '',
        modules: {
          toolbar: {
            container: [
              ['code-block'],
              [{ 'direction': 'rtl' }],
              ['bold', 'italic', 'underline', 'strike'],
              [{ 'color': [] }],
              [{ 'background': [] }],
              [{ 'header': 1 }, { 'header': 2 }],
              [{ 'script': 'sub' }, { 'script': 'super' }],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              [{ 'indent': '-1' }, { 'indent': '+1' }],
              [{ 'font': ['sans-serif', 'monospace', 'serif'] }],
              [{ 'size': ['small', false, 'large', 'huge'] }],
              [{ 'align': [] }],
              ['link'],
              ['clean'],
              ['insertMetric']
            ],
            handlers: {
              insertMetric: this.handleToken
            }
          }
        },
        theme: 'snow',
        placeholder: ''
      },
    }
  },
  created () {
    this.init()
  },
  methods: {
    setSignature (val) {
      this.javaMailProperties_mail_smtp_signing = val.javaMailProperties_mail_smtp_signing||''
    },
    deleteMore () {
      let arr = this.$refs.multipleTable.selection
      this.deleteSmtp(arr)
    },
    keyWordsChange: debounce(function () {
      this.init()
    }, 1000),
    addOrUpdata (row) {
      this.userformData = {
        formCode: config.systemSettingMail,
        formTitle: 'Options',
        id: row.id
      }
      this.isEdit = !!row.id;
      !this.isEdit && (this.javaMailProperties_mail_smtp_signing = '')
    },
    openDialog (row) {
      this.dialogVisible = true
      this.addOrUpdata(row)
    },
    init () {
      this.currentPage = 1
      this.total = 0
      this.tableData = []
      this.getSmtpList()
    },
    async getSmtpList () {
      this.loading = true
      let params = {
        current: this.currentPage,
        size: this.size,
        username: this.keyValue
      }
      const { getSmtpList } = this.$interface.reports
      const { data: res } = await getSmtpList(params)
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.tableData = res.data.records
      this.total = res.data.total
      this.loading = false
    },
    deleteSmtp (arr) {
      if (arr.length === 0) {
        return this.$message.error('Please select the row to delete')
      }
      this.$confirm(this.$t('custom.apps.deleteconfirm'), this.$t('custom.apps.warning'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        // type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(async () => {
        this.loading = true
        let params = arr.map(i => i.id)
        const { deleteSmtp } = this.$interface.reports
        const { data: res } = await deleteSmtp(params)
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.getSmtpList()
        this.$message.success('Delete succeeded')
        // this.loading = false
      })
    },
    handleClick (row) {
      this.openDialog(row)
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
      this.getSmtpList()
    },
    closeHanlder () {
      this.$refs.userFormMaking.resetFormMaking()
      this.dialogVisible = false
    },
    add () {
      this.$refs.userFormMaking.$refs.generateForm.getData()
        .then(async(data) => {
          // data.username
          // this.userformData.id
          // this.loading = true
          let params = {
            id:this.userformData.id,
            username: data.username
          }
          const { getSmtpCheck } = this.$interface.reports
          const { data: res } = await getSmtpCheck(params)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$refs.userFormMaking.addOrUpdateFormData(null, this.javaMailProperties_mail_smtp_signing,this.isEdit)
        })
    },
    async handleTestConnection () {
      this.$refs.userFormMaking.$refs.generateForm
        .getData()
        .then(async data => {
          this.connectionloading = true
          let form = {}
          Object.keys(data).forEach(key => {
            if (!key.includes('text')) form[key] = data[key]
          })
          try {
            await this.$interface.system.testConnectionSystemMail(form)
            this.$message.success('Connection Succeeded')
            this.connectionloading = false
          } catch (err) {
            if (err.response.status === 500)
              this.$message.error('Connection Failed')
            this.connectionloading = false
          }
        })
    },
    async handleEvent (data) {
      this.closeHanlder()
      this.getSmtpList()
      this.postEmailVerify(data)
    },
    async postEmailVerify (db) {
      let params = {
        id: db.id,
        username: db.username || db.dataContent.username
      }
      const { postEmailVerify } = this.$interface.reports
      const { data: res } = await postEmailVerify(params)
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.$alert(`We have sent a verification email to ${db.username || db.dataContent.username}.Click the verify button in the email to verify your email.`, 'Verify Email Address', {
        confirmButtonText: 'OK'
      }).then(() => {
        var hash = {
          'qq.com': 'http://mail.qq.com',
          'gmail.com': 'http://mail.google.com',
          'sina.com': 'http://mail.sina.com.cn',
          '163.com': 'http://mail.163.com',
          '126.com': 'http://mail.126.com',
          'yeah.net': 'http://www.yeah.net/',
          'sohu.com': 'http://mail.sohu.com/',
          'tom.com': 'http://mail.tom.com/',
          'sogou.com': 'http://mail.sogou.com/',
          '139.com': 'http://mail.10086.cn/',
          'hotmail.com': 'http://www.hotmail.com',
          'live.com': 'http://login.live.com/',
          'live.cn': 'http://login.live.cn/',
          'live.com.cn': 'http://login.live.com.cn',
          '189.com': 'http://webmail16.189.cn/webmail/',
          'yahoo.com.cn': 'http://mail.cn.yahoo.com/',
          'yahoo.cn': 'http://mail.cn.yahoo.com/',
          'eyou.com': 'http://www.eyou.com/',
          '21cn.com': 'http://mail.21cn.com/',
          '188.com': 'http://www.188.com/',
          'foxmail.com': 'http://www.foxmail.com',
          'outlook.com': 'http://www.outlook.com'
        }
        let h = (db.host||db.dataContent.host).replace('smtp.', '')
        window.open(hash[h], '_blank')
      })
    }
  }
}
</script>